package com.xuedongzhilian.service.impl;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.entity.CheckIn;
import com.xuedongzhilian.mapper.CheckInMapper;
import com.xuedongzhilian.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 * 打卡记录服务实现类
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {

    @Override
    public Result getCheckInStreak(Long userId, Integer type) {
        // 查询用户所有打卡记录，按日期倒序排列
        List<CheckIn> checkIns = this.lambdaQuery()
                .eq(CheckIn::getUserId, userId)
                .eq(CheckIn::getType, type)
                .orderByDesc(CheckIn::getCheckInDate)
                .list();
                
        if (checkIns.isEmpty()) {
            return Result.ok(0);
        }
        
        // 计算连续打卡天数
        int streak = 0;
        LocalDate today = LocalDate.now();
        LocalDate expectedDate = today;
        
        for (CheckIn checkIn : checkIns) {
            LocalDate checkInDate = checkIn.getCheckInDate();
            
            // 如果打卡日期等于期望日期
            if (checkInDate.equals(expectedDate)) {
                streak++;
                // 期望日期减一天
                expectedDate = expectedDate.minusDays(1);
            } else {
                // 如果打卡日期不连续，跳出循环
                break;
            }
        }
        
        return Result.ok(streak);
    }
}